package cn.yunyichina.provider.message.thread.app;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.framework.dubbo.service.WechatPayService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.message.dao.TmpTemplateDao;
import cn.yunyichina.provider.message.dao.TmpTemplateListDao;
import cn.yunyichina.provider.message.entity.OrgAppTemplate;
import cn.yunyichina.provider.message.entity.TmpTemplate;
import cn.yunyichina.provider.message.entity.TmpTemplateList;
import cn.yunyichina.provider.message.utils.MsgAppUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 模板消息线程
 * Created by Joe.zhou on 2017/12/13.
 */
public class MsgTmpAppPushRunnable implements Runnable{
    private static Logger logger = LoggerFactory.getLogger(MsgTmpAppPushRunnable.class);

    private final String METHOD_NAME = "MsgTmpAppPushRunnable";

    private AppMessageVo appMessageVo;

    private ResponseObject responseObject;

    private TmpTemplateDao tmpTemplateDao = SpringContextHandler.getBean(TmpTemplateDao.class);

    private TmpTemplateListDao tmpTemplateListDao = SpringContextHandler.getBean(TmpTemplateListDao.class);

    public MsgTmpAppPushRunnable(AppMessageVo appMessageVo, ResponseObject responseObject) {
        this.appMessageVo = appMessageVo;
        this.responseObject = responseObject;
    }

    @Override
    public void run() {
        Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.REQUEST,appMessageVo.getOpenId(), JsonUtils.toJsonString(appMessageVo));
        try {
            if(appMessageVo != null){
                OrgAppTemplate orgAppTemplat = MsgAppUtils.getOrgAppTemplat(JsonUtils.toJsonString(appMessageVo));

                //获取推送模板表信息
                TmpTemplate tmpTemplate = new TmpTemplate();
                tmpTemplate.setTemplateCode(orgAppTemplat.getLibraryTemplateCode());
                tmpTemplate.setPlatformType(orgAppTemplat.getPlatformType());
                List<TmpTemplate> tmpTemplates = tmpTemplateDao.select(tmpTemplate);
                if(tmpTemplates.size() < 1){
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取TmpTemplate失败：" + JsonUtils.toJsonString(tmpTemplate));
                    responseObject.setResultCodeAndMessage("8203" , "获取TmpTemplate失败：" + JsonUtils.toJsonString(tmpTemplate));
                    return;
                }
                tmpTemplate = tmpTemplates.get(0);
                String url = tmpTemplate.getUrl();
                if(StringUtils.isBlank(url)){
                    url = appMessageVo.getUrl();
                }
                logger.info("MsgTmpAppPushRunnable 获取到模板链接url：" + url);

                //获取推送模板详情信息
                TmpTemplateList tmpTemplateList = new TmpTemplateList();
                tmpTemplateList.setTmpTemplateId(tmpTemplate.getId());
                List<TmpTemplateList> templateLists = tmpTemplateListDao.select(tmpTemplateList);
                if(templateLists.size() < 1){
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取TmpTemplateList失败：" + JsonUtils.toJsonString(tmpTemplateList));
                    responseObject.setResultCodeAndMessage("8203" , "获取TmpTemplateList失败：" + JsonUtils.toJsonString(tmpTemplateList));
                    return;
                }

                //集合根据sort排序
                Collections.sort(templateLists, new Comparator<TmpTemplateList>(){
                    @Override
                    public int compare(TmpTemplateList a, TmpTemplateList b) {
                        if (a.getSort() > b.getSort()) {
                            return 1;
                        }
                        return -1;
                    }
                });

                //获取支付配置
                PaymentSettingResponse paymentSettingResponse = MsgAppUtils.getPaymentSettingResponse(appMessageVo.getPlatformOrgAppCode() ,
                        StringUtils.isBlank(appMessageVo.getDevOrgCode())? "" : appMessageVo.getDevOrgCode() , orgAppTemplat.getPlatformType().intValue());
                if(paymentSettingResponse == null){
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    responseObject.setResultCodeAndMessage("8203" , "MsgTmpAppPushRunnable 获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    return;
                }

                JSONObject param = new JSONObject();
                Map<String,Object> resContentMap = new HashMap<String,Object>();
                Response response = null;
                //根据推送平台不同分发
                if(orgAppTemplat.getPlatformType() == 1){  //微信

                    //组装Wechat.content
                    resContentMap = MsgAppUtils.getResultWechatMsgContentMap(templateLists, appMessageVo);
                    logger.info("Wechat替换成功后msg_content：" + JSON.toJSONString(resContentMap));

                    if(resContentMap.size() < 1){
                        Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"Wechat 未匹配到模板元素字段，请检查配置");
                        responseObject.setResultCodeAndMessage("8203" , "Wechat 未匹配到模板元素字段，请检查配置");
                        return;
                    }

                    param.put("payment_setting" , paymentSettingResponse);
                    param.put("to_user" , appMessageVo.getOpenId());
                    param.put("template_id" , orgAppTemplat.getPayTemplateId());
                    param.put("url" , url);
                    param.put("msg_content" , JSON.toJSONString(resContentMap));

                    //调用wechat发送消息
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat模板消息发送："+ JsonUtils.toJsonString(param));
                    response = WechatPayService.callHumpFromInternal("yyt.wechatpay.wechat.message.template.send", JsonUtils.toJsonString(param));
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat模板消息返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgTmpAppPushRunnable 调用Wechat模板消息返回：" + response.getResultMessage());
                }else if(orgAppTemplat.getPlatformType() == 2){ //支付宝

                    //组装Alipay.content
                    List<Object> alipayMsgContents = MsgAppUtils.getResultAlipayMsgContentMap(templateLists, appMessageVo);
                    logger.info("Alipay替换成功后msg_content：" + JSON.toJSONString(alipayMsgContents));

                    //解析和设置内容参数
                    param.put("list_msg_template_content" , JSON.toJSONString(alipayMsgContents));
                    param.put("org_app_code" , appMessageVo.getPlatformOrgAppCode());
                    param.put("org_code" , appMessageVo.getDevOrgCode());
                    param.put("template_id" , orgAppTemplat.getPayTemplateId());
                    param.put("head_color" , tmpTemplate.getTopColor());
                    param.put("platform_type" , appMessageVo.getPlatformType());
                    param.put("to_user" , appMessageVo.getOpenId());
                    param.put("template_id" , orgAppTemplat.getPayTemplateId());
                    param.put("url" , url);
                    param.put("payment_setting" , paymentSettingResponse);

                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay模板消息发送："+ JsonUtils.toJsonString(param));
                    response = AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.template.send", JsonUtils.toJsonString(param));
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay模板消息发送返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgTmpAppPushRunnable 调用Alipay模板消息返回：" + response.getResultMessage());
                }else{
                    Log.i(LogScene.MSG_TMP,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    responseObject.setResultCodeAndMessage("8203" , "获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    return;
                }
            }
        } catch (Exception e) {
            Log.e(LogScene.MSG_TMP , "MsgTmpAppPushRunnable 执行方法异常！" , e);
            responseObject.setResultCodeAndMessage(Response.FAILURE_CODE , "MsgTmpAppPushRunnable 执行方法异常！");
        }
    }

}
